package com.grj.star.interceptor;


import com.grj.star.annotation.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;


/**
 * @author 14505
 */
@Slf4j
public class LogInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Log methodAnnotation = handlerMethod.getMethodAnnotation(Log.class);
        if (methodAnnotation!= null) {
            long startTime = System.currentTimeMillis();
            request.setAttribute("startTime", startTime);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView){
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        Log methodAnnotation = handlerMethod.getMethodAnnotation(Log.class);
        Object startTime = request.getAttribute("startTime");
        if (methodAnnotation!= null && startTime!= null) {
            long endTime = System.currentTimeMillis();
            log.info("请求地址：{}，请求描述：{}，请求方式：{}，请求方法：{}，请求耗时：{}ms", request.getRequestURI(), methodAnnotation.desc(), request.getMethod(), method.getDeclaringClass().getName()+"#"+method.getName(), endTime - (long) startTime);
        }
    }
}
